/***************************************************************************
 *      pyinput.cpp
 * 
 *      Description: The class for reading input files written in python
 *		
 *      Copyright 2012 Artem Korzhimanov <korzhimanov.artem@gmail.com>
 *      
 *      This program is free software; you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation; either version 2 of the License, or
 *      (at your option) any later version.
 *      
 *      This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *      
 *      You should have received a copy of the GNU General Public License
 *      along with this program; if not, write to the Free Software
 *      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 *      MA 02110-1301, USA.
 ***************************************************************************/

#include "pyinput.h"

using namespace std;

pyinput::pyinput()
{
	Py_Initialize();
	main_module = PyImport_AddModule("__main__");
	main_dict = PyModule_GetDict(main_module);
	PyRun_SimpleString("from math import *");
	PyRun_SimpleString("def sqr(x):\n\treturn x*x");
}

pyinput::~pyinput()
{
	if (f != NULL) fclose(f);
	Py_Finalize();
}

void pyinput::ReadFile(string filename)
{
	f = fopen(filename.c_str(), "r");
	PyRun_SimpleFile(f, filename.c_str());
}

int pyinput::GetInt(string name)
{
	return PyInt_AsLong(PyDict_GetItemString(main_dict, name.c_str()));
}

double pyinput::GetDouble(string name)
{
	return PyFloat_AsDouble(PyDict_GetItemString(main_dict, name.c_str()));
}

string pyinput::GetString(string name)
{
	return string(PyString_AsString(PyDict_GetItemString(main_dict, name.c_str())));
}

pFunc pyinput::GetFunc(string name)
{
	pFunc func(PyDict_GetItemString(main_dict, name.c_str()));
	return func;
}
